<template>
  <div class="box">
    <div class="header">
      <van-nav-bar
        title="购物车"
        left-text="返回"
        right-text="清空购物车"
        left-arrow
        @click-left="onClickLeft"
        @click-right="removeAll"
      />
    </div>
    <div class="main">
      <div class="nothing" v-if="empty">
        <van-empty
          class="custom-image"
          image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
          description="购物车为空"
        />
      </div>
      <div class="hasthing" v-else>
        <van-swipe-cell
          v-for="(item, index) in cartList"
          :key="index"
          :name="item.cartid"
          :before-close="beforeClose"
        >
          <!-- beforeClose: 包含了一个name属性，这个name属性的执行 就是name属性的值 -->
          <van-checkbox
            style="padding-left: 20px"
            v-model="item.flag"
            @click="selectOne(item.cartid, item.flag)"
          />
          <van-card
            :price="item.originprice"
            :title="item.proname"
            :thumb="item.img1"
          >
            <template #num>
              <van-stepper
                v-model="item.num"
                theme="round"
                button-size="22"
                disable-input
                @change="updateNum(item.cartid, item.num)"
              />
            </template>
          </van-card>
          <!-- 删除 -->
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
      </div>
      <!-- 为你推荐 -->
      <div>
        <van-divider
          :style="{
            color: '#1989fa',
            borderColor: '#1989fa',
            padding: '0 16px',
          }"
        >
          为你推荐
        </van-divider>
      </div>
      <!-- 猜你喜欢 -->
      <div
        style="display: flex; flex-wrap: wrap; justify-content: space-around"
      >
        <div
          style="
            width: 47%;
            border-radius: 10px;
            margin-top: 10px;
            background-color: #fff;
          "
          v-for="(item, index) in proList"
          :key="index"
          @click="jumpTo1(item.proid)"
        >
          <img
            style="width: 100%; border-radius: 10px 10px 0 0"
            :src="item.img1"
            alt=""
          />
          <div>
            <h4 class="van-multi-ellipsis--l2">{{ item.proname }}</h4>
            <p class="prices" style="color: red">￥{{ item.originprice }}</p>
          </div>
        </div>
      </div>
      <!-- 提交地址栏 -->
      <div>
        <van-submit-bar
          :price="sum() * 100"
          button-text="提交订单"
          style="margin-bottom: 44px"
          @submit="onSubmit"
        >
          <van-checkbox v-model="isAll">全选</van-checkbox>
        </van-submit-bar>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Empty,
  Card,
  Stepper,
  SwipeCell,
  Checkbox,
  CheckboxGroup,
  Dialog,
  SubmitBar,
  Divider,
} from "vant";

Vue.use(SubmitBar);
Vue.use(Card);
Vue.use(Empty);
Vue.use(Dialog);
Vue.use(Stepper);
Vue.use(SwipeCell);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Divider);
import { doRecommendList } from "../api/home";
import { addOrder } from "../api/order";
import {
  doCartList, //查看购物车
  doUpdateNum, //更新购物车数量
  doDeleteOne, //删除单个
  doDeleteAll, //删除所有
  doSelectAll, //全选
  doSelectOne, //单选
} from "../api/cart";
export default {
  name: "Cart",
  components: {},
  data() {
    return {
      empty: true,
      cartList: [],
      proList: [],
      // time:""
    };
  },
  created() {
    doRecommendList().then((data) => {
      console.log(data.data.data);
      this.proList = data.data.data;
    });
    // 判断用户是否登陆
    if (localStorage.getItem("token")) {
      this.getCartList();
    } else {
      //  去到登陆页
      this.$router.push("/login");
    }
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    jumpTo1(proid) {
      this.$router.push("/detail/" + proid);
      // this.$router.push({ path: "/detail", params: { proid } });
      window.location.reload(); //页面自动刷新
    },
    updateNum(cartid, num) {
      // console.log(cartid, num);
      // 调用 增加数量的接口
      doUpdateNum({ cartid, num }).then((res) => {
        console.log("更新购物车数量", res.data);
      });
    },
    getCartList() {
      // 发送 获取购物车的请求
      doCartList({ userid: localStorage.getItem("userid") }).then((res) => {
        console.log(res.data.code);
        if (res.data.code == "10020") {
          // 没有数据
          this.empty = true;
        } else {
          // 有数据
          this.empty = false;
          this.cartList = res.data.data;
        }
      });
    },
    beforeClose({ name, position, instance }) {
      console.log(name, position, instance);
      switch (position) {
        case "right":
          Dialog.confirm({
            message: "确定删除吗？",
          })
            .then(() => {
              // 点击了确定删除就在执行这里
              doDeleteOne({ cartid: name }).then((res) => {
                console.log(res);
                if (res.data.code == "200") {
                  this.getCartList();
                }
              });
              instance.close();
            })
            .catch(() => {
              instance.close();
            });
          break;
      }
    },
    selectOne(cartid, flag) {
      doSelectOne({ cartid: cartid, flag: flag }).then((res) => {
        console.log("删除单个成功", res);
      });
    },
    removeAll() {
      Dialog.alert({
        message: "亲.你确定要删除吗?",
      }).then(() => {
        doDeleteAll({ userid: localStorage.getItem("userid") })
          .then((res) => {
            console.log(res.data);
            console.log(res.data.code);
            if (res.data.code == 200) {
              console.log("删除所有商品成功", res.data);
              Dialog({ message: "删除所有商品成功" });
            }
            window.location.reload();
          })
          .catch(() => {});
      });
    },
    sum() {
      // 累加计算
      var total = 0;
      this.cartList.forEach((item) => {
        if (item.flag) {
          total += item.originprice * item.num;
        }
      });
      return total;
    },
    onSubmit(){
      addOrder().then(res=>{
        console.log(res);
        if(res.data.code==200){
          console.log(res.data.time);
            // localStorage.setItem(res.data.time)
          this.$router.push("/confimgods/"+res.data.time)
        }
      })
    },
  },
  computed: {
    //getter方法决定了 isAll 是上面全部选中 isAll结果就是true，  有一个是false，isAll就是false
    isAll: {
      set(val) {
        console.log(val);
        this.cartList.forEach((item) => (item.flag = val));
        doSelectAll({ userid: localStorage.getItem("userid"), type: val }).then(
          (res) => {
            console.log(res);
          }
        );
      },
      get() {
        return this.cartList.every((item) => item.flag == true);
      },
    },
  },
};
</script>

<style scoped>
.delete-button {
  height: 100%;
}
::v-deep .van-swipe-cell__wrapper {
  display: flex;
  background-color: #fff;
}
::v-deep .van-checkbox {
  width: 0.6rem;
}
::v-deep .van-card {
  flex: 1;
  background-color: #fff;
}
</style>